package com.z.redis.datatype;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Redis的Hash类型
 */
public class RedisHash implements RedisData{
    private volatile long timeout = -1;
    private final Map<BytesWrapper, BytesWrapper> map = new ConcurrentHashMap<>();

    /**
     * Hset key field value
     * @param field
     * @param value
     * @return 1/0
     */
    public int put(BytesWrapper field, BytesWrapper value) {
        // 如果字段是新增的返回1 覆盖旧值返回0
        return map.put(field, value) == null ? 1 : 0;
    }

    /**
     * Hgetall key
     * @return 所有的键值对
     */
    public Map<BytesWrapper, BytesWrapper> getMap() {
        return map;
    }

    /**
     * hdel key field [field ...]
     * @param fields
     * @return 删除的个数
     */
    public int del(List<BytesWrapper> fields) {
        return (int) fields.stream().filter(key -> map.remove(key) != null).count();
    }

    /**
     * hget key
     * @param field
     * @return 对应的value
     */
    public BytesWrapper get(BytesWrapper field) {
        return map.get(field);
    }


    /**
     * hlen key
     * @return hash表中的字段个数
     */
    public int size(){
        return map.size();
    }

    @Override
    public long getTimeout() {
        return timeout;
    }
    @Override
    public void setTimeout(long timeout) {
        this.timeout = timeout;
    }
}
